<template>
    <Transition name="slide">
        <div v-if="showUpdateNotification" class="update-notification">
            <span>发现新版本，请刷新页面以使用最新功能</span>
            <div class="actions">
                <button @click="refreshPage" class="refresh-btn">立即刷新</button>
                <button @click="closeNotification" class="close-btn">稍后再说</button>
            </div>
        </div>
    </Transition>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { registerServiceWorker, printCachedRequests } from '@/utils/serviceWorkerUtil';

const showUpdateNotification = ref(false);
// let registration: ServiceWorkerRegistration | null | 
const refreshPage = async () => {
    // sendMessage('来自页面的消息1')
    printCachedRequests()
    window.location.reload();
};

const closeNotification = () => {
    showUpdateNotification.value = false;
};

onMounted(() => {
    registerServiceWorker((event: any) => {
        console.log('event', event)
        if (event.type === 'update') {
            showUpdateNotification.value = true;
        }
    });
});
</script>

<style scoped lang="less">
.update-notification {
    position: fixed;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    background: #fff;
    padding: 16px 24px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    display: flex;
    align-items: center;
    gap: 16px;
    z-index: 9999;

    .actions {
        display: flex;
        gap: 8px;
    }

    button {
        padding: 6px 12px;
        border-radius: 4px;
        cursor: pointer;
        border: none;
        font-size: 14px;

        &.refresh-btn {
            background: #1890ff;
            color: white;
        }

        &.close-btn {
            background: #f5f5f5;
            color: #666;
        }
    }
}

.slide-enter-active,
.slide-leave-active {
    transition: all 0.3s ease;
}

.slide-enter-from,
.slide-leave-to {
    transform: translate(-50%, 100%);
    opacity: 0;
}
</style>